import Message from "@/components/message";
import axios from "axios";
import useStore from "@/stores";

// 备用接口地址: http://pcapi-xiaotuxian-front-devtest.itheima.net/
const instance = axios.create({
  // baseURL: "http://pcapi-xiaotuxian-front.itheima.net/",
  baseURL: " http://pcapi-xiaotuxian-front-devtest.itheima.net/",
  // timeout: 5000,
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const { user } = useStore();
    const token = user.userInfo.token;

    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  // 成功响应
  (response) => {
    return response;
  },
  // 失败响应
  (error) => {
    // 失败  响应状态码 2xx 3xx 4xx 5xx
    // 4xx 5xx
    // console.log(error);
    if (error.response) {
      Message.error(error.response.data.message);
    }

    return Promise.reject(error);
  }
);

export default instance;
